<!--
 * @Author: your name
 * @Date: 2021-07-20 21:04:14
 * @LastEditTime: 2021-07-21 22:35:42
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \lix-management\src\views\experiment\DragAction.vue
-->
<template>
  <div class="rootbox" ref="rootbox" @mousemove="mouseMove" @mouseup="mouseUp">
    <div ref="box" class="box">
      <div class="header" @mousedown="mouseDown">拖拽我</div>
      <div class="body"></div>
    </div>
  </div>
</template>
<script>
export default {
  name: "ex-drag",
  data() {
    return {
      // 是否在拖拽中
      isDraging: false,
      // 点击的位置与 box左上角 的距离
      mouseOffsetX: 0,
      mouseOffsetY: 0
    };
  },
  methods: {
    mouseDown(e) {
      let boxDom = this.$refs.box;
      this.mouseOffsetX = e.pageX - boxDom.offsetLeft;
      this.mouseOffsetY = e.pageY - boxDom.offsetTop;
      this.isDraging = true;
    },
    mouseMove(e) {
      // 鼠标当前位置
      let mouseX = e.pageX;
      let mouseY = e.pageY;
      // box 左上角的新位置
      let moveX;
      let moveY;

      let boxDom = this.$refs.box;

      if (this.isDraging) {
        moveX = mouseX - this.mouseOffsetX;
        moveY = mouseY - this.mouseOffsetY;

        let pageWidth = this.$refs.rootbox.clientWidth;
        let pageHeight = this.$refs.rootbox.clientHeight;

        let boxWidth = this.$refs.box.offsetWidth;
        let boxHeight = this.$refs.box.offsetHeight;

        // 能移动的最大位置
        let maxX = pageWidth - boxWidth;
        let maxY = pageHeight - boxHeight;

        moveX = Math.min(maxX, Math.max(0, moveX));
        moveY = Math.min(maxY, Math.max(0, moveY));

        boxDom.style.left = moveX + "px";
        boxDom.style.top = moveY + "px";
      }
    },
    mouseUp(e) {
      this.isDraging = false;
    }
  }
};
</script>
<style lang="less" scoped>
.rootbox {
  height: 100%;
  position: relative;
}
.box {
  height: 500px;
  width: 500px;
  position: absolute;
  .header {
    height: 60px;
    line-height: 60px;
    background-color: #ccc;
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    cursor: move;
  }
  .body {
    height: 440px;
    background-color: #e8e8e8;
  }
}
</style>
